import React, { useState, useEffect, useRef } from 'react';
import cls from 'classnames';
import styles from './index.less';
import { Table, Modal, Button, message, Switch } from 'antd';
import { useDebounce } from 'react-use';
import {
  SearchOutlined,
  LinkOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  CloseSquareOutlined,
} from '@ant-design/icons';

import {
  getModelListByProjId,
  addModelToProjId,
  deleteModels,
  updateModel,
  getServicesListByProjId,
  addServiceToProjId,
  updateService,
  deleteServices,
} from '@/services/modelManageService';

function isImgService(objectId) {
  return /s_/.test(objectId);
}

/**
 * 项目管理
 */
const ModelManageRight = ({ curProj }) => {
  const [isShowAddModal, setIsShowAddModal] = useState(false);
  const [isShowURLModal, setIsShowURLModal] = useState('');
  const [curUrl, setCurUrl] = useState('');
  const [curModelList, setCurModelList] = useState([]);
  const curEditingRef = useRef();
  const [keyword, setKeyword] = useState('');
  const [dKeyword, setDKeyword] = useState('');
  const [isAddService, setIsAddService] = useState(false);

  const curSelectRef = useRef([]);
  const nameRef = useRef();
  const urlRef = useRef();
  const singleUrlRef = useRef();

  useEffect(() => {
    if (!curProj) return;
    _getModelListByProjId(curProj);
    setKeyword('');
    return () => {};
  }, [curProj]);

  const [, cancel] = useDebounce(
    () => {
      setDKeyword(keyword);
    },
    800,
    [keyword],
  );

  // 刷新模型list
  async function _getModelListByProjId(curProj) {
    const { data } = await getModelListByProjId(curProj);
    // todo
    let { data: _servicesData } = await getServicesListByProjId(curProj);
    _servicesData.modelList = _servicesData.modelList || [];

    let servicesList = _servicesData.modelList.map(e => {
      e._objectId = e.objectId;
      e.objectId = 's_' + e.objectId;
      return e;
    });
    let modelList = (data && data.modelList) || [];
    // setCurModelList(modelList);
    setCurModelList(modelList.concat(servicesList));
  }

  // 添加模型
  async function handleItemAdd() {
    if (!curProj) return;
    let url = urlRef.current.value;
    let name = nameRef.current.value;
    if (!name) {
      message.info('名称为必填');
      return;
    }

    let addFn = isAddService ? addServiceToProjId : addModelToProjId;
    await addFn({
      label: '',
      menuId: curProj,
      name,
      url,
    });

    setIsShowAddModal(false);
    urlRef.current.value = '';
    nameRef.current.value = '';
    _getModelListByProjId(curProj);
  }

  function handleAddCancel() {
    setIsShowAddModal(false);
  }

  function handleUrlEditClick(item) {
    curEditingRef.current = item;
    setIsShowURLModal(item.name);
    setTimeout(() => {
      singleUrlRef.current.value = item.url;
    }, 60);
  }

  function handleURLCancel() {
    setIsShowURLModal('');
    curEditingRef.current = null;
    singleUrlRef.current.value = '';
  }

  // 更新模型url
  async function handleURLModify() {
    if (!curEditingRef.current) return;
    console.log({ ...curEditingRef.current, url: singleUrlRef.current.value });
    let updateFn = updateModel;
    let updateItem = { ...curEditingRef.current, url: singleUrlRef.current.value };
    if (isImgService(updateItem.objectId)) {
      updateFn = updateService;
      updateItem.objectId = updateItem._objectId;
    }

    await updateFn(updateItem);
    handleURLCancel();
    _getModelListByProjId(curProj);
  }

  async function handleVisiableToggle(item) {
    let updateItem = { ...item, visible: !item.visible };
    let updateFn = updateModel;
    if (isImgService(item.objectId)) {
      updateFn = updateService;
      updateItem.objectId = updateItem._objectId;
    }
    await updateFn(updateItem);
    _getModelListByProjId(curProj);
  }

  async function handleModelsDelete() {
    if (!curSelectRef.current.length) return;
    const [mIds, sIds] = curSelectRef.current.reduce(
      (r, objectId) => {
        if (isImgService(objectId)) {
          r[1].push(objectId.slice(2));
        } else {
          r[0].push(objectId);
        }
        return r;
      },
      [[], []],
    );
    mIds.length && (await deleteModels(mIds));
    sIds.length && (await deleteServices(sIds));
    _getModelListByProjId(curProj);
  }

  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      curSelectRef.current = selectedRowKeys;
      // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    getCheckboxProps: record => ({
      // disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  const columns = [
    {
      title: '标题',
      dataIndex: 'name',
    },
    {
      title: '修改日期',
      dataIndex: 'modifyDate',
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      width: 160,
      render: record => {
        return (
          <div className={styles.tableBtn}>
            {/* 影像服务不需要链接 */}
            <LinkOutlined
              className={styles.tableBtnItem}
              onClick={() => handleUrlEditClick(record)}
            />

            {record.visible ? (
              <EyeOutlined
                className={styles.tableBtnItem}
                onClick={() => handleVisiableToggle(record)}
              />
            ) : (
              <EyeInvisibleOutlined
                className={styles.tableBtnItem}
                onClick={() => handleVisiableToggle(record)}
              />
            )}
          </div>
        );
      },
    },
  ];

  return (
    <div className={styles.right}>
      <div style={{ padding: '26px 0 10px', opacity: 0.7 }}>{`模型总数：${
        curModelList ? curModelList.length : 0
      }`}</div>
      <h4 style={{ fontSize: 20, color: '#fff' }}>项目列表</h4>
      <div className={styles.rightTitle}>
        <div className={cls(styles.rightSearch)}>
          <SearchOutlined></SearchOutlined>
          <input
            placeholder="搜索当前列表"
            value={keyword}
            onChange={e => setKeyword(e.target.value)}
            type="text"
          />
        </div>

        <div className={styles.rightBtns}>
          <div className={cls(styles.rightBtn, styles.rightBtnPrimary)} onClick={() => setIsShowAddModal(true)}>
            创建
          </div>
          <div onClick={handleModelsDelete} className={cls(styles.rightBtn)}>
            删除
          </div>
        </div>
      </div>
      <div className={styles.rightBody}>
        <Table
          rowKey="objectId"
          rowSelection={{
            ...rowSelection,
          }}
          columns={columns}
          dataSource={curModelList.filter(({ name }) => {
            if (!dKeyword) return true;
            return name.indexOf(dKeyword) !== -1;
          })}
          pagination={{ position: 'left' }}
        />
      </div>
      <Modal
        title={
          <span>
            <span style={{ display: 'inline-block', width: 108 }}>
              {isAddService ? '添加影像数据' : '添加模型数据'}{' '}
            </span>
            <Switch
              size="small"
              style={{ marginTop: -2 }}
              value={isAddService}
              onChange={() => {
                setIsAddService(e => !e);
              }}
            />
          </span>
        }
        wrapClassName={styles.cModal}
        visible={isShowAddModal}
        onOk={handleItemAdd}
        onCancel={handleAddCancel}
        footer={null}
        width={280}
        centered
        closeIcon={<CloseSquareOutlined />}
      >
        <p>{isAddService ? '影像文件名' : '模型文件名'} *</p>
        <input placeholder="请输入文件名称" ref={nameRef} type="text" />
        <p>URL地址</p>
        <input placeholder="请输入URL地址" ref={urlRef} type="text" />
        <div className="" style={{ textAlign: 'center', paddingBottom: 8 }}>
          <Button className={styles.cButton} key="done" onClick={handleItemAdd}>
            完成
          </Button>
        </div>
      </Modal>
      <Modal
        title="URl"
        wrapClassName={styles.cModal}
        visible={isShowURLModal}
        onOk={handleURLModify}
        onCancel={handleURLCancel}
        footer={null}
        width={380}
        centered
        closeIcon={<CloseSquareOutlined />}
      >
        <div className="">
          <input
            placeholder="请输入URL地址"
            ref={singleUrlRef}
            style={{ width: 260, marginRight: 14 }}
            type="text"
          />
          <Button className={styles.cButton} key="done" onClick={handleURLModify}>
            确认
          </Button>
        </div>
      </Modal>
    </div>
  );
};

export default ModelManageRight;
